'''
Created on 23/03/2009

@author: eh01
'''
from BaseHTTPServer import BaseHTTPRequestHandler
from yarra.datastore import dsconstants
from yarra.datastore.dso import DSO
from yarra.datastore.dst import DST
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventmanager import EventManager
from yarra.logging import yarralogging
import datetime
import threading


class NodeHTTPRequestHandler(BaseHTTPRequestHandler):
    '''
    HTTPRequestHandler handles all http requests
    '''
    __logger = yarralogging.get_logger(yarralogging.WEBSERVER)
    
    def handle_request(self):
        self.__logger.debug(self.headers)
        self.__logger.info('Start Request: ' + str(datetime.datetime.now()))
        dst1 = DST(subject=dsconstants.SUBJECT_ROOT, predicate=dsconstants.PREDICATE_HTTP_REQUEST, literal=self)
        # http://docs.python.org/library/threading.html#id2
        # create a lock initially unlocked.
        lock = threading.Lock()
        lock.acquire()
        # add it to a DST (because an event handler will release it one day) using lock.release()
        dst2 = DST(subject=dsconstants.SUBJECT_ROOT, predicate=dsconstants.PREDICATE_LOCK, literal=lock)
        dso = DSO(dsts=[dst1, dst2])
        event = Event(eventconstants.HTTP_REQUEST_EVENT_TYPE, dso)
        EventManager().add_event(event)
      
        # second acquire(), blocks until the lock.release() called in other thread
        # once the lock has been released, the lock is acquired again
        lock.acquire()
        # call the release immediately, as there is no synchronized code we want to run
        lock.release()
        self.__logger.info('End Request: ' + str(datetime.datetime.now()))
        return
    
    def do_GET(self):        
        self.handle_request()
        return
    
    def do_POST(self):
        self.handle_request()
        return
    
    def do_PUT(self):
        self.handle_request()
        return
    
    def do_DELETE(self):
        self.handle_request()
        return